import { MiddlewareConsumer, Module, NestModule } from "@nestjs/common";
import { WinstonModule } from "nest-winston";
import winstonLogger from "./config/winston.config";
import { LoggerMiddleware } from "./middleware/logger.middleware";
import { ConfigModule, ConfigService } from "@nestjs/config";
import envConfig from "@/config/index.config";
import { TypeOrmModule } from "@nestjs/typeorm";
import { RedisModule } from "./redis/redis.module";
import { CacheModule } from "@nestjs/cache-manager";
import { redisStore } from "cache-manager-redis-yet";
import { RedisClientOptions } from "redis";
import { UsersModule } from "./modules/users/users.module";
import { AuthModule } from "./modules/auth/auth.module";
@Module({
	imports: [
		ConfigModule.forRoot({
			isGlobal: true, // 设置为全局
			cache: true,
			envFilePath: [envConfig.path]
		}),
		WinstonModule.forRoot({
			transports: winstonLogger.transports,
			format: winstonLogger.format,
			defaultMeta: winstonLogger.defaultMeta,
			exitOnError: false // 防止意外退出
		}),
		TypeOrmModule.forRootAsync({
			imports: [ConfigModule],
			inject: [ConfigService],
			useFactory: async (configService: ConfigService) => ({
				type: "mysql", // 数据库类型
				// entities: [],  // 数据表实体
				entities: ["dist/**/*.entity{.ts,.js}"],
				host: configService.get("DB_HOST"), // 主机，默认为localhost
				port: configService.get<number>("DB_PORT"), // 端口号
				username: configService.get("DB_USER"), // 用户名
				password: configService.get("DB_PASSWORD"), // 密码
				database: configService.get("DB_DATABASE"), //数据库名
				timezone: "+08:00", //服务器上配置的时区
				synchronize: true, //根据实体自动创建数据库表， 生产环境建议关闭
				autoLoadEntities: true, // 自动导入实体
				maxQueryExecutionTime: 1000 // 记录超过1秒的查询
			})
		}),
		CacheModule.registerAsync<RedisClientOptions>({
			imports: [ConfigModule],
			inject: [ConfigService],
			isGlobal: true,
			useFactory: async (configService: ConfigService) => ({
				store: redisStore,
				host: configService.get("REDIS_HOST"),
				port: Number(configService.get("REDIS_PORT")),
				password: configService.get("REDIS_PASSWORD"),
				database: parseInt(configService.get("REDIS_DB"), 10)
			})
		}),
		RedisModule,
		AuthModule,
		UsersModule
	],
	controllers: [],
	providers: []
})
export class AppModule implements NestModule {
	configure(consumer: MiddlewareConsumer) {
		consumer.apply(LoggerMiddleware).forRoutes("*");
	}
}
